const sys = require(`./system.js`)
const title = '助学抢购-common'
const $ = sys.$(title)

const task = 'task:common'
// const task = 'task:small'
const localStorage = 'localStorage-2'
sys.run($, 'task:one', (resList, cookie, index, username, password, item) => {
    return new Promise(async resolve => {
        // 请求接口
        const size = 300
        const day = 160
        let novice = false
        if (['task:small2', 'task:small'].includes(task)) {
          novice = true
        }
        const list = await $.publicJS.equitiesList($, cookie, size, day, novice)
        const maxCha = 40
        const couponsConfig = [200, 300, 400, 500, 700, 800]
        let couponList = $.localStorage.get(`couponList-${task}`, localStorage) || []
        let commonList = $.localStorage.get(task, localStorage)
        // 存在最优购买组合
        while (list.length > 0) {
            let zyList = zy(list, couponsConfig, Math.max(...couponsConfig) + maxCha * 4)
            console.log('zyList', zyList)
            zyList = zyList.filter(it => it.cha < maxCha)
            console.log('过滤 zyList', zyList)
            for (let i = 0; i < zyList.length; i++) {
                const zy = zyList[i]
                console.log(zy, zy)
                // 权益组合总金额
                const sum = zy.coupon + zy.cha
                const coupons = findCoupons(couponList, commonList, sum, zy.coupon)
                console.log('coupons', coupons)
                if (!coupons) {
                    continue;
                }
                username = coupons.username
                cookie = await $.publicJS.checkCookie($, $.localStorage.get(`${username}-cookie`, 'localStorage'), username, password)
                const ids = zy.list.map(item => (list.find(it => it['金额'] == item).id))
                const qys = zy.list.map(item => {
                    const qy = (list.find(it => it['金额'] == item))
                    return {
                        'id': qy['id'],
                        '金额': qy['金额']
                    }
                })
                const resp = await $.publicJS.buy($, cookie, ids, coupons.id, novice, sum)
                console.log('resp', resp)
                // 追加信息
                resList.push({
                    '序号': index + 1,
                    username: username,
                    qys: JSON.stringify(qys),
                    coupons: {
                        id: coupons.id,
                        amount: coupons.amount,
                        note: coupons.note,
                        useCondition: coupons.useCondition,
                        day: coupons.day
                    },
                    resp: resp.message
                })
                // 删除优惠卷
                if (resp.code == 200) {
                    if (coupons && coupons.id) {
                        let idx = couponList.findIndex(it => it.id == coupons.id)
                        if (idx > -1) {
                            couponList.splice(idx, 1)
                        }
                        $.localStorage.set(`couponList-${task}`, couponList, localStorage)
                    }
                    let idx = commonList.findIndex(it => it.username == username)
                    if (idx > -1) {
                        commonList[idx]['账户余额'] = commonList[idx]['账户余额'] - sum
                    }
                    $.localStorage.set(task, commonList, localStorage)
                } else {
                    $.notify.sendNotify(title, `购买失败 ${resp.message}`)
                    resolve(resList)
                }
            }
            break;
        }

        resolve(resList)
    })
}, (resList) => {
    console.log('任务结束 resList:', resList)
    if (resList && resList.length > 0) {
        const resListStr = JSON.stringify(resList, null, 2)
        $.notify.sendNotify(title, resListStr)
    }
})

/**
 * 查找可用优惠卷 同时账户余额足够
 * @param {*} couponList 优惠卷列表
 * @param {*} commonList 账户列表
 * @param {*} amount     权益金额
 * @param {*} useCoupon     优惠卷可用金额
 */
function findCoupons(couponList, commonList, amount, useCoupon) {
    let fList = couponList
        // 筛选可用的优惠卷金额
        .filter(item => item.useCondition == useCoupon)
        .map(item => ({
            ...item,
            userAmount: commonList.find(it => it.username == item.username)['账户余额']
        }));
    console.log('满足可用金额，fList', useCoupon, fList)
    fList = fList.filter(item => item.userAmount > amount)
    if (fList && fList.length > 0) {
        const coupon = fList[0]
        console.log(`[查找优惠卷] - [成功] - [${coupon.username}] - [余额 ${coupon.userAmount}] - [权益 ${amount}] [优惠卷可用金额 ${useCoupon}]`)
        return coupon;
    }
    console.log(`[查找优惠卷] - [无匹配] - [权益 ${amount}] [优惠卷可用金额 ${useCoupon}]`)
}


function getAllCombinations(arr, start = 0, currentCombination = [], allCombinations = [], targetSum = Infinity) {
    const currentSum = currentCombination.reduce((acc, val) => acc + val, 0);

    if (currentSum > targetSum) {
        return;
    }

    if (currentCombination.length > 0) {
        allCombinations.push(currentCombination.slice());
    }

    for (let i = start; i < arr.length; i++) {
        currentCombination.push(arr[i]);
        getAllCombinations(arr, i + 1, currentCombination, allCombinations, targetSum);
        currentCombination.pop();
    }

    return allCombinations;
}

function findMinExcessCombination(prices, coupon) {
    const list = prices.map((item, index) => {
        // 使用reduce方法来计算数组的和
        const sum = item.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
        return {
            index: index,
            list: item,
            coupon: coupon,
            cha: Number((sum - coupon).toFixed(2))
        }
    }).filter(item => item.cha > 0)
    const minNum = Math.min(...list.map(item => item.cha))
    return list.filter(item => item.cha === minNum)[0]
}

function zy(list, coupons, maxNum) {
    let prices = Array.from(new Set(list.map(item => item['金额']).filter(item => item < maxNum)))
    prices.sort((a, b) => a - b);
    console.log('prices', prices, prices.length)


    console.time("allCombinations方法计算耗时");
    // 获取商品价格所有组合
    const allCombinations = getAllCombinations(prices, 0, [], [], maxNum);
    console.timeEnd("allCombinations方法计算耗时");

    console.time("findMinExcessCombination方法计算耗时");
    // 获取最优商品组合
    const resList = coupons.map(item => {
        return findMinExcessCombination(allCombinations, item)
    })
    resList.sort((a, b) => a.cha - b.cha);
    console.timeEnd("findMinExcessCombination方法计算耗时");
    return resList;
}